const { spawn } = require('child_process');
const EventEmitter = require('events');


class TopEmitter extends EventEmitter {};
const topEmitter = new TopEmitter();
let proc = null; // 进程
const new_parser = require('./topparse');

// 开始
topEmitter.start = (options = {}) => {
    const processData = (_data) => {
        try {
			let start = _data.indexOf('top ');
			let end = _data.indexOf('top ', start + 1);
			if (end == -1 || end == start) {
                return;
            }
			let data = _data.slice(start,end);
			let result = {};
			try {
				result = new_parser(data, options, error => {
                    topEmitter.emit('error', { error });
                });
			} catch(error) {
				topEmitter.emit('error', {error:error});
			}
            topEmitter.emit('data', result);
            top_data = _data.replace(data, '');
			return true;
		} catch(error) {
            topEmitter.emit("error",{error});
        }
    };
    proc = spawn('top');
    let topData = '';
    proc.stdout.on('data', data => {
        topData += data;
        processData(topData);
    });
}
// 停止
topEmitter.stop = () => {
    if (proc) {
        proc.kill('SIGINT');
    }
}
module.exports = topEmitter;